﻿/**
* userCtrl - AngularJS module for right sidebar.
*
*
* Credits
* =======
*
* Copyright 2015 LonghronShen <LonghronShen@Hotmail.com>
*/

function translateRealNameState(value) {
    //None = 0,
    //Uncommitted = 1,
    //Pending = 2,
    //Pass = 3,
    //NotPass = 4
    // console.info("translateRealNameState: ", value);
    switch (value) {
        case 0:
            return "无效";

        case 1:
            return "未提交";

        case 2:
            return "未审核";

        case 3:
            return "已通过";

        case 4:
            return "未通过";
    }
};
function translateRolesEngligh(x) {
    switch (x) {
        case "Administator": return '管理员'; break;
        case "Carrier": return '承运商'; break;
        case "Driver": return '司机'; break;
        case "Staff": return '员工'; break;
        case "System": return '系统'; break;
        default: return '';
    }
}
function translateIsLockedout(value) {
    if (value == true) {
        return '是';
    } else if (value == false) { return '否'; }
}
function getStateResult(clickRemovePassState, clickOkPassState) {
    if (clickRemovePassState == true && clickOkPassState == true) {
        return 2;
    } else if (clickRemovePassState == false) {
        return 4;
    } else if (clickOkPassState == false) {
        return 3;
    }
}
(function () {
    "use strict";

    /**
     * Config
     */
    var moduleName = 'app';
    var DEFAULT_ID = '__default';

    /**
     * Module
     */
    var module;
    try {
        module = angular.module(moduleName);
    } catch (err) {
        // named module does not exist, so create one
        module = angular.module(moduleName, []);
    }

    module.controller('userCtrl', ['$scope', '$ngBootbox', '$stateParams', 'dataService', '$state', function ($scope, $ngBootbox, $stateParams, dataService, $state) {
        // console.info("<userCtrl> Defining userCtrl...");

        $scope.searchingKeyword = "";
        $scope.searchingRoleId = "";
        $scope.searchingCarcode = "";
        $scope.searchingState = "";

        $scope.searchingStartTime = moment("0001-01-01").toDate();
        $scope.searchingEndTime = new Date();

        var skip = $scope.skip = 0;
        var count = $scope.count = 10;

        //角色
        $scope.roles = [];
        var str = [];
        //用户ID
        var UserIdEdit;
        //审核状态枚举
        $scope.checkState = [{ text: '无效', value: '0' }, { text: '未提交', value: '1' }, { text: '未审核', value: '2' }, { text: '已通过', value: '3' }, { text: '未通过', value: '4' }];

        $scope.selectedUser = {};
        //初始化列表
        var loadUsers = function (keyword, carCode, startTime, endTime, roleId, state, skip, count, useCache) {
            dataService.getUsers(keyword, carCode, startTime, endTime, roleId, state, useCache == null ? false : useCache, skip, count).then(function (res) {
                //res = res.data || { Response: { Output: { List: [] } } };
                res = res.data;
                // console.info("loadUsers: getUsers returned: ", res);
                var list = res.Response.List;
                // console.info("loadUsers: list: ", list);
                for (var i = 0; i < list.length; i++) {
                    list[i].Id = i + 1 + (skip * count);
                    list[i].RealNameState = translateRealNameState(list[i].RealNameState);
                    list[i].roles = translateRealRoles(list[i].Roles);
                    list[i].isLockedout = list[i].IsLockedout;
                    list[i].IsLockedout = translateIsLockedout(list[i].IsLockedout);
                }
                //$scope.gridApi.grid.options.totalItems = res.result.total;
                $scope.gridApi.grid.options.totalItems = res.Response.Total;
                console.info("loadUsers: list test1: ", list);
                $scope.userList = { data: list };
                var currentPage = $scope.gridApi.grid.options.paginationCurrentPage;
                var totalPages = $scope.gridApi.pagination.getTotalPages();
                if (totalPages < currentPage) { $scope.gridApi.grid.options.paginationCurrentPage = 1; };
            }, function (rej) {
                $ngBootbox.alert(rej);
            });
        };


        //分页初始化
        var paginationOptions = {
            pageNumber: 0,
            pageSize: 10,
            currentPage: 1,
            sort: null,
            useCache: true
        };
        var _userList = $scope.userList = {
            data: [],
            enableSorting: false,
            paginationPageSizes: [10, 20, 30],
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            columnDefs: [
                { displayName: "序号", field: 'Id', enableColumnMenu: false, },
                { displayName: "车牌号", field: 'CarNumber', enableColumnMenu: false },
                { displayName: "车型", field: 'CarType', enableColumnMenu: false },
                { displayName: "车长", field: 'CarLength', enableColumnMenu: false },
                { displayName: "用户名", field: 'UserName', enableColumnMenu: false },
                { displayName: "真实姓名", field: 'RealName', enableColumnMenu: false },
                { displayName: '实名认证状态', field: 'RealNameState', enableColumnMenu: false, },
                { displayName: '实名申请时间', field: 'CertificationTime', enableColumnMenu: false, },
                { displayName: '禁用', field: 'IsLockedout', enableColumnMenu: false, },
                { displayName: '角色', field: 'roles', enableColumnMenu: false },
                {
                    displayName: "操作",
                    field: '操作',
                    cellFilter: 'checkmark',
                    cellTemplate: '../../../tpl/app_management_user_table_cell.html',
                    enableColumnMenu: false
                }
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    paginationOptions.pageNumber = newPage * pageSize - pageSize;
                    paginationOptions.pageSize = pageSize;
                    paginationOptions.currentPage = newPage;
                    $scope.gridApi.grid.options.paginationCurrentPage = newPage;
                    $scope.skip = paginationOptions.pageNumber;
                    $scope.count = paginationOptions.pageSize;
                    loadUsers($scope.searchingKeyword, $scope.searchingCarcode, $scope.searchingStartTime,
                        $scope.searchingEndTime, $scope.searchingRoleId, $scope.searchingState,
                        parseInt(newPage - 1), paginationOptions.pageSize, paginationOptions.useCache);
                    paginationOptions.useCache = true;
                });
            }
        };

        loadUsers($scope.searchingKeyword, $scope.searchingCarcode, $scope.searchingStartTime,
            $scope.searchingEndTime, $scope.searchingRoleId, $scope.searchingState,
            paginationOptions.pageNumber, paginationOptions.pageSize, false);

        //角色
        dataService.getUserRoles().then(function (res) {
            //console.info("getUserRoles returned: ", res.data.Response.UserRoles);
            for (var m = 0; m < res.data.Response.length; m++) {
                var StrElement = { 'Id': res.data.Response[m].Id, 'Name': res.data.Response[m].Name, 'chineseName': translateRolesEngligh(res.data.Response[m].Name) };
                str.push(StrElement);
            }
            //console.info('str',str);
            $scope.roles = str;
            //console.info("$scope.roles ", $scope.roles);
        }, function (rej) {
            $ngBootbox.alert(rej);
        });

        //角色转换
        function translateRoles(id) {
            //console.info("$scope.roles1 ", $scope.roles);
            var UserRole = $scope.roles;
            for (var z = 0; z < UserRole.length; z++) {
                if (id == UserRole[z].Id) {
                    //console.info('测试UserRole[z].chineseName', UserRole[z].chineseName);
                    return UserRole[z].chineseName;
                }
            }
        }
        function translateRealRoles(roleList) {
            var name = '';
            for (var j = 0; j < roleList.length; j++) {
                name += translateRoles(roleList[j]) + ',';
            }
            //console.info('测试', name);
            return name.substring(0, name.length - 1);
        };
        //end角色转换


        //查询调用
        $scope.queryUsers = function () {
            paginationOptions.pageNumber = 0;
            paginationOptions.currentPage = 1;
            paginationOptions.useCache = false;
            $scope.gridApi.pagination.raise.paginationChanged(paginationOptions.currentPage, paginationOptions.pageSize);
        };

        //删除
        $scope.deleteUser = function (userId) {
            $ngBootbox.confirm('是否删除该用户').then(function () {
                dataService.deleteAccount(userId).then(function (res) {
                    paginationOptions.useCache = false;
                    $scope.gridApi.pagination.raise.paginationChanged(paginationOptions.currentPage, paginationOptions.pageSize);
                }, function (rej) { $ngBootbox.alert(rej); })
            }, function () {
                return;
            });
        };
        //启用
        $scope.disabledStar = function (userId) {
            $ngBootbox.confirm('是否启用该权限').then(function () {
                dataService.setAccountLockoutState(userId, false).then(function (res) {
                    paginationOptions.useCache = false;
                    $scope.gridApi.pagination.raise.paginationChanged(paginationOptions.currentPage, paginationOptions.pageSize);
                }, function (rej) {
                    $ngBootbox.alert(rej)
                });
            }, function () {
                return;
            });
        }
        //禁用
        $scope.disableUser = function (userId) {
            $ngBootbox.confirm('是否禁用该用户').then(function () {
                dataService.setAccountLockoutState(userId, true).then(function (res) {
                    paginationOptions.useCache = false;
                    $scope.gridApi.pagination.raise.paginationChanged(paginationOptions.currentPage, paginationOptions.pageSize);
                }, function (rej) { $ngBootbox.alert(rej); })
            }, function () {
                return;
            });
        };
        //状态转换
        function imgState(imgStates) {
            if (imgStates == true) {
                return true;
            } else { return false; }
        }
        //获取详情
        $scope.editUserDetail = function (user) {
            // console.info("$scope.editUserDetail: ", user);
            var userId = user.UserId;
            UserIdEdit = user;
            dataService.getRealNameInfo(userId).then(function (res) {
                try {
                    // console.info("getRealNameInfo returned: ", res);
                    $scope.selectedUser = res.data.Response;
                    $scope.selectedUser.UserId = userId;
                    $scope.selectedUser.UserName = user.RealName || user.UserName || user.PhoneNumber;
                    $scope.selectedUser.CarCode = $scope.selectedUser.CarCode;

                    $scope.RealHeadImageSatus = translateRealNameState($scope.selectedUser.RealHeadState);
                    $scope.IDCardImageSatus = translateRealNameState($scope.selectedUser.IDCardState);
                    $scope.DrivingLicenseImageSatus = translateRealNameState($scope.selectedUser.DrivingLicenseState);
                    $scope.VehicleLicenseImageSatus = translateRealNameState($scope.selectedUser.VehicleLicenseState);

                    $scope.RealHeadImageTool = $scope.selectedUser.RealHeadState == 2 && $scope.selectedUser.RealHeadImage !== null;
                    $scope.IDCardImageTool = $scope.selectedUser.IDCardState == 2 && $scope.selectedUser.IDCardImage !== null;
                    $scope.DrivingLicenseImageTool = $scope.selectedUser.DrivingLicenseState == 2 && $scope.selectedUser.DrivingLicenseImage !== null;
                    $scope.VehicleLicenseImageTool = $scope.selectedUser.VehicleLicenseState == 2 && $scope.selectedUser.VehicleLicenseImage !== null;

                    $scope.clickOkPassState = $scope.clickIDCardOkPassState = $scope.clickDrivingLicenseOkPassState = $scope.clickVehicleLicenseOkPassState = true;
                    $scope.clickRemovePassState = $scope.clickIDCardRemovePassState = $scope.clickDrivingLicenseRemovePassState = $scope.clickVehicleLicenseRemovePassState = true;

                    $scope.selectedUser.RealHeadImageCertificated = res.data.Response.RealHeadState;
                    $scope.selectedUser.IdCardCertificated = res.data.Response.IDCardState;
                    $scope.selectedUser.DrivingLicenseCertificated = res.data.Response.DrivingLicenseState;
                    $scope.selectedUser.VehicleLicenseCertificated = res.data.Response.VehicleLicenseState;

                    $scope.clickOk = function (statusValue) {

                        switch (statusValue) {
                            case "RealHeadImage": return $scope.clickOkPassState = false, $scope.selectedUser.RealHeadImageCertificated = getStateResult($scope.clickRemovePassState, $scope.clickOkPassState); break;
                            case "IDCardImage": return $scope.clickIDCardOkPassState = false, $scope.selectedUser.IdCardCertificated = getStateResult($scope.clickIDCardRemovePassState, $scope.clickIDCardOkPassState); break;
                            case "DrivingLicenseImage": return $scope.clickDrivingLicenseOkPassState = false, $scope.selectedUser.DrivingLicenseCertificated = getStateResult($scope.clickDrivingLicenseRemovePassState, $scope.clickDrivingLicenseOkPassState); break;
                            case "VehicleLicenseImage": return $scope.clickVehicleLicenseOkPassState = false, $scope.selectedUser.VehicleLicenseCertificated = getStateResult($scope.clickVehicleLicenseRemovePassState, $scope.clickVehicleLicenseOkPassState); break;
                        }

                    }
                    $scope.clickOkPass = function (statusValue) {
                        switch (statusValue) {
                            case "RealHeadImage": return $scope.clickOkPassState = true, $scope.selectedUser.RealHeadImageCertificated = getStateResult($scope.clickRemovePassState, $scope.clickOkPassState); break;
                            case "IDCardImage": return $scope.clickIDCardOkPassState = true, $scope.selectedUser.IdCardCertificated = getStateResult($scope.clickIDCardRemovePassState, $scope.clickIDCardOkPassState); break;
                            case "DrivingLicenseImage": return $scope.clickDrivingLicenseOkPassState = true, $scope.selectedUser.DrivingLicenseCertificated = getStateResult($scope.clickDrivingLicenseRemovePassState, $scope.clickDrivingLicenseOkPassState); break;
                            case "VehicleLicenseImage": return $scope.clickVehicleLicenseOkPassState = true, $scope.selectedUser.VehicleLicenseCertificated = getStateResult($scope.clickVehicleLicenseRemovePassState, $scope.clickVehicleLicenseOkPassState); break;
                        }

                    }
                    $scope.clickRemove = function (statusValue) {
                        switch (statusValue) {
                            case "RealHeadImage": return $scope.clickRemovePassState = false, $scope.selectedUser.RealHeadImageCertificated = getStateResult($scope.clickRemovePassState, $scope.clickOkPassState); break;
                            case "IDCardImage": return $scope.clickIDCardRemovePassState = false, $scope.selectedUser.IdCardCertificated = getStateResult($scope.clickIDCardRemovePassState, $scope.clickIDCardOkPassState); break;
                            case "DrivingLicenseImage": return $scope.clickDrivingLicenseRemovePassState = false, $scope.selectedUser.DrivingLicenseCertificated = getStateResult($scope.clickDrivingLicenseRemovePassState, $scope.clickDrivingLicenseOkPassState); break;
                            case "VehicleLicenseImage": return $scope.clickVehicleLicenseRemovePassState = false, $scope.selectedUser.VehicleLicenseCertificated = getStateResult($scope.clickVehicleLicenseRemovePassState, $scope.clickVehicleLicenseOkPassState); break;
                        }

                    }
                    $scope.clickRemovePass = function (statusValue) {
                        switch (statusValue) {
                            case "RealHeadImage": return $scope.clickRemovePassState = true, $scope.selectedUser.RealHeadImageCertificated = getStateResult($scope.clickRemovePassState, $scope.clickOkPassState); break;
                            case "IDCardImage": return $scope.clickIDCardRemovePassState = true, $scope.selectedUser.IdCardCertificated = getStateResult($scope.clickIDCardRemovePassState, $scope.clickIDCardOkPassState); break;
                            case "DrivingLicenseImage": return $scope.clickDrivingLicenseRemovePassState = true, $scope.selectedUser.DrivingLicenseCertificated = getStateResult($scope.clickDrivingLicenseRemovePassState, $scope.clickDrivingLicenseOkPassState); break;
                            case "VehicleLicenseImage": return $scope.clickVehicleLicenseRemovePassState = true, $scope.selectedUser.VehicleLicenseCertificated = getStateResult($scope.clickVehicleLicenseRemovePassState, $scope.clickVehicleLicenseOkPassState); break;
                        }

                    }

                    $scope.selectedUser.IDCardImage = $scope.selectedUser.IDCardImage || "img/a0.jpg";
                    $scope.selectedUser.DrivingLicenseImage = $scope.selectedUser.DrivingLicenseImage || "img/a0.jpg";
                    $scope.selectedUser.VehicleLicenseImage = $scope.selectedUser.VehicleLicenseImage || "img/a0.jpg";
                    $scope.selectedUser.RealHeadImage = $scope.selectedUser.RealHeadImage || "img/a0.jpg"

                    $('#myModal').modal('show');
                }
                catch (e) {
                    $ngBootbox.alert(e);
                }
            }, function (rej) {
                $ngBootbox.alert(rej);
            });
        };
        //编辑（保存）
        $scope.submitUserInfo = function () {
            var list = {
                UserId: $scope.selectedUser.UserId,
                CarCode: $scope.selectedUser.CarCode,
                DrivingLicenseKeyStatus: $scope.selectedUser.DrivingLicenseCertificated,
                RealHeadKeyStatus: $scope.selectedUser.RealHeadImageCertificated,
                IdCardKeyStatus: $scope.selectedUser.IdCardCertificated,
                VehicleLicenseKeyStatus: $scope.selectedUser.VehicleLicenseCertificated
            };
            dataService.putUserRealNameCertificationStatus($scope.selectedUser.UserId,list);
            $('#myModal').modal('hide');
        };
        //跳转至用户强制修改页面
        $scope.linkToUsersEdit = function () {
            console.info(111);
            $state.go("app.management.user_edit", { UserId: UserIdEdit.UserId, RealName: UserIdEdit.RealName, UserName: UserIdEdit.UserName, PhoneNumber: UserIdEdit.PhoneNumber, Roles: UserIdEdit.Roles });
            $('#myModal').modal('hide');
        }
    }]);
    //用户强制修改
    module.controller('userEditCtrl', ['$scope', '$ngBootbox', '$stateParams', 'FileUploader', 'routeService', 'azureBlob', 'dataService', '$state', function ($scope, $ngBootbox, $stateParams, FileUploader, routeService, azureBlob, dataService, $state) {
        console.info('test twice', $stateParams);
        $scope.searchingKeyword = "";
        $scope.searchingRoleId = "";
        $scope.searchingCarcode = '';
        $scope.searchingState = "2";

        $scope.searchingStartTime = moment("0001-01-01").toDate();
        $scope.searchingEndTime = new Date();

        var skip = $scope.skip = 0;
        var count = $scope.count = 10;

        $scope.RealHeadImage = null; $scope.IDCardImage = null; $scope.DrivingLicenseImage = null; $scope.VehicleLicenseImage = null;
        //角色
        $scope.roles = [];
        var str = [];
        //初始化列表
        var loadUsers = function (keyword, carCode, startTime, endTime, roleId, state, skip, count, useCache) {
            dataService.getUsers(keyword, carCode, startTime, endTime, roleId, state, useCache == null ? false : useCache, skip, count).then(function (res) {
                //res = res.data || { Response: { Output: { List: [] } } };
                res = res.data;
                // console.info("loadUsers: getUsers returned: ", res);
                var list = res.Response.List;
                // console.info("loadUsers: list: ", list);
                for (var i = 0; i < list.length; i++) {
                    list[i].Id = i + 1 + (skip * count);
                    list[i].RealNameState = translateRealNameState(list[i].RealNameState);
                    list[i].roles = translateRealRoles(list[i].Roles);
                    list[i].isLockedout = list[i].IsLockedout;
                    list[i].IsLockedout = translateIsLockedout(list[i].IsLockedout);
                }
                //$scope.gridApi.grid.options.totalItems = res.result.total;
                $scope.gridApi.grid.options.totalItems = res.Response.Total;
                console.info("loadUsers: list test1: ", list);
                $scope.userList = { data: list };
                var currentPage = $scope.gridApi.grid.options.paginationCurrentPage;
                var totalPages = $scope.gridApi.pagination.getTotalPages();
                if (totalPages < currentPage) { $scope.gridApi.grid.options.paginationCurrentPage = 1; };
            }, function (rej) {
                $ngBootbox.alert(rej);
            });
        };


        //分页初始化
        var paginationOptions = {
            pageNumber: 0,
            pageSize: 10,
            currentPage: 1,
            sort: null,
            useCache: true
        };
        var _userList = $scope.userList = {
            data: [],
            enableSorting: false,
            paginationPageSizes: [10, 20, 30],
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            columnDefs: [
                { displayName: "序号", field: 'Id', enableColumnMenu: false, },
                { displayName: "车牌号", field: 'CarNumber', enableColumnMenu: false },
                { displayName: "车型", field: 'CarType', enableColumnMenu: false },
                { displayName: "车长", field: 'CarLength', enableColumnMenu: false },
                { displayName: "用户名", field: 'UserName', enableColumnMenu: false },
                { displayName: "真实姓名", field: 'RealName', enableColumnMenu: false },
                { displayName: '实名认证状态', field: 'RealNameState', enableColumnMenu: false, },
                { displayName: '实名申请时间', field: 'CertificationTime', enableColumnMenu: false, },
                { displayName: '禁用', field: 'IsLockedout', enableColumnMenu: false, },
                { displayName: '角色', field: 'roles', enableColumnMenu: false },
                {
                    displayName: "操作",
                    field: '操作',
                    cellFilter: 'checkmark',
                    cellTemplate: '<a data-toggle="modal" class="fa fa-edit m-l-xs primary text-info" title="编辑" ng-click="grid.appScope.editUserDetail(row.entity)"></a>',
                    enableColumnMenu: false
                }
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    paginationOptions.pageNumber = newPage * pageSize - pageSize;
                    paginationOptions.pageSize = pageSize;
                    paginationOptions.currentPage = newPage;
                    $scope.gridApi.grid.options.paginationCurrentPage = newPage;
                    $scope.skip = paginationOptions.pageNumber;
                    $scope.count = paginationOptions.pageSize;
                    loadUsers($scope.searchingKeyword, $scope.searchingCarcode, $scope.searchingStartTime,
                        $scope.searchingEndTime, $scope.searchingRoleId, $scope.searchingState,
                        parseInt(newPage - 1), paginationOptions.pageSize, paginationOptions.useCache);
                    paginationOptions.useCache = true;
                });
            }
        };

        loadUsers($scope.searchingKeyword, $scope.searchingCarcode, $scope.searchingStartTime,
            $scope.searchingEndTime, $scope.searchingRoleId, $scope.searchingState,
            paginationOptions.pageNumber, paginationOptions.pageSize, false);

        //角色
        dataService.getUserRoles().then(function (res) {
            // console.info("getUserRoles returned: ", res.data.Response.UserRoles);
            for (var m = 0; m < res.data.Response.length; m++) {
                var StrElement = { 'Id': res.data.Response[m].Id, 'Name': res.data.Response[m].Name, 'chineseName': translateRolesEngligh(res.data.Response[m].Name) };
                str.push(StrElement);
            }
            // console.info('str',str);
            $scope.roles = str;
        }, function (rej) {
            $ngBootbox.alert(rej);
        });

        //角色转换
        function translateRoles(id) {
            // console.info("$scope.roles1 ", $scope.roles);
            var UserRole = $scope.roles;
            for (var z = 0; z < UserRole.length; z++) {
                if (id == UserRole[z].Id) {
                    return UserRole[z].chineseName;
                }
            }
        }
        function translateRealRoles(roleList) {
            var name = '';
            for (var j = 0; j < roleList.length; j++) {
                name += translateRoles(roleList[j]) + ',';
            }
            return name.substring(0, name.length - 1);
        };
        //end角色转换



        function Detail(user) {
            console.info("$scope.editUserDetail: ", user);
            var userId = user.UserId;
            dataService.getRealNameInfo(userId).then(function (res) {
                try {
                    // console.info("getRealNameInfo returned: ", res);
                    $scope.selectedUser = res.data.Response;
                    $scope.selectedUser.UserId = userId;
                    $scope.selectedUser.UserName = user.RealName || user.UserName || user.PhoneNumber;
                    $scope.selectedUser.CarCode = $scope.selectedUser.CarCode;
                    $scope.selectedUser.PhoneNumber = user.PhoneNumber;
                    $scope.selectedUser.RealName = user.RealName;
                    $scope.selectedUser.UserNameReal = user.UserName;
                    //角色多选
                    $scope.RolesList = str;
                    if (Object.prototype.toString.call(user.Roles) == "[object Null]") {
                        $scope.RolesCheckedList = [];
                    } else if (Object.prototype.toString.call(user.Roles) == "[object String]") {
                        $scope.RolesCheckedList = user.Roles.split(',');
                    } else if (Object.prototype.toString.call(user.Roles) == "[object Array]") {
                        $scope.RolesCheckedList = user.Roles;
                    }

                    console.info('$scope.RolesCheckedList', $scope.RolesCheckedList)
                    //click选中权限
                    $scope.autClick = function () {
                        var RolesArr = $scope.RolesCheckedList;
                        console.info('RolesArr', RolesArr);
                    }

                    $scope.RealHeadImageSatus = translateRealNameState($scope.selectedUser.RealHeadState);
                    $scope.IDCardImageSatus = translateRealNameState($scope.selectedUser.IDCardState);
                    $scope.DrivingLicenseImageSatus = translateRealNameState($scope.selectedUser.DrivingLicenseState);
                    $scope.VehicleLicenseImageSatus = translateRealNameState($scope.selectedUser.VehicleLicenseState);

                    $scope.RealHeadUpLoad = $scope.selectedUser.RealHeadState == 3 || $scope.selectedUser.RealHeadState == 4 || $scope.selectedUser.RealHeadImage !== null;
                    $scope.IDCardUpLoad = $scope.selectedUser.IDCardState == 3 || $scope.selectedUser.IDCardState == 4 || $scope.selectedUser.IDCardImage !== null;
                    $scope.DrivingLicenseUpLoad = $scope.selectedUser.DrivingLicenseState == 3 || $scope.selectedUser.DrivingLicenseState == 4 || $scope.selectedUser.DrivingLicenseImage !== null;
                    $scope.VehicleLicenseUpLoad = $scope.selectedUser.VehicleLicenseState == 3 || $scope.selectedUser.VehicleLicenseState == 4 || $scope.selectedUser.VehicleLicenseImage !== null;

                    $scope.RealHeadImageTool = $scope.selectedUser.RealHeadState == 2 && $scope.selectedUser.RealHeadImage !== null;
                    $scope.IDCardImageTool = $scope.selectedUser.IDCardState == 2 && $scope.selectedUser.IDCardImage !== null;
                    $scope.DrivingLicenseImageTool = $scope.selectedUser.DrivingLicenseState == 2 && $scope.selectedUser.DrivingLicenseImage !== null;
                    $scope.VehicleLicenseImageTool = $scope.selectedUser.VehicleLicenseState == 2 && $scope.selectedUser.VehicleLicenseImage !== null;

                    $scope.clickOkPassState = $scope.clickIDCardOkPassState = $scope.clickDrivingLicenseOkPassState = $scope.clickVehicleLicenseOkPassState = true;
                    $scope.clickRemovePassState = $scope.clickIDCardRemovePassState = $scope.clickDrivingLicenseRemovePassState = $scope.clickVehicleLicenseRemovePassState = true;

                    $scope.selectedUser.RealHeadImageCertificated = res.data.Response.RealHeadState;
                    $scope.selectedUser.IdCardCertificated = res.data.Response.IDCardState;
                    $scope.selectedUser.DrivingLicenseCertificated = res.data.Response.DrivingLicenseState;
                    $scope.selectedUser.VehicleLicenseCertificated = res.data.Response.VehicleLicenseState;

                    $scope.clickOk = function (statusValue) {

                        switch (statusValue) {
                            case "RealHeadImage": return $scope.clickOkPassState = false, $scope.selectedUser.RealHeadImageCertificated = getStateResult($scope.clickRemovePassState, $scope.clickOkPassState); break;
                            case "IDCardImage": return $scope.clickIDCardOkPassState = false, $scope.selectedUser.IdCardCertificated = getStateResult($scope.clickIDCardRemovePassState, $scope.clickIDCardOkPassState); break;
                            case "DrivingLicenseImage": return $scope.clickDrivingLicenseOkPassState = false, $scope.selectedUser.DrivingLicenseCertificated = getStateResult($scope.clickDrivingLicenseRemovePassState, $scope.clickDrivingLicenseOkPassState); break;
                            case "VehicleLicenseImage": return $scope.clickVehicleLicenseOkPassState = false, $scope.selectedUser.VehicleLicenseCertificated = getStateResult($scope.clickVehicleLicenseRemovePassState, $scope.clickVehicleLicenseOkPassState); break;
                        }

                    }
                    $scope.clickOkPass = function (statusValue) {
                        switch (statusValue) {
                            case "RealHeadImage": return $scope.clickOkPassState = true, $scope.selectedUser.RealHeadImageCertificated = getStateResult($scope.clickRemovePassState, $scope.clickOkPassState); break;
                            case "IDCardImage": return $scope.clickIDCardOkPassState = true, $scope.selectedUser.IdCardCertificated = getStateResult($scope.clickIDCardRemovePassState, $scope.clickIDCardOkPassState); break;
                            case "DrivingLicenseImage": return $scope.clickDrivingLicenseOkPassState = true, $scope.selectedUser.DrivingLicenseCertificated = getStateResult($scope.clickDrivingLicenseRemovePassState, $scope.clickDrivingLicenseOkPassState); break;
                            case "VehicleLicenseImage": return $scope.clickVehicleLicenseOkPassState = true, $scope.selectedUser.VehicleLicenseCertificated = getStateResult($scope.clickVehicleLicenseRemovePassState, $scope.clickVehicleLicenseOkPassState); break;
                        }

                    }
                    $scope.clickRemove = function (statusValue) {
                        switch (statusValue) {
                            case "RealHeadImage": return $scope.clickRemovePassState = false, $scope.selectedUser.RealHeadImageCertificated = getStateResult($scope.clickRemovePassState, $scope.clickOkPassState); break;
                            case "IDCardImage": return $scope.clickIDCardRemovePassState = false, $scope.selectedUser.IdCardCertificated = getStateResult($scope.clickIDCardRemovePassState, $scope.clickIDCardOkPassState); break;
                            case "DrivingLicenseImage": return $scope.clickDrivingLicenseRemovePassState = false, $scope.selectedUser.DrivingLicenseCertificated = getStateResult($scope.clickDrivingLicenseRemovePassState, $scope.clickDrivingLicenseOkPassState); break;
                            case "VehicleLicenseImage": return $scope.clickVehicleLicenseRemovePassState = false, $scope.selectedUser.VehicleLicenseCertificated = getStateResult($scope.clickVehicleLicenseRemovePassState, $scope.clickVehicleLicenseOkPassState); break;
                        }

                    }
                    $scope.clickRemovePass = function (statusValue) {
                        switch (statusValue) {
                            case "RealHeadImage": return $scope.clickRemovePassState = true, $scope.selectedUser.RealHeadImageCertificated = getStateResult($scope.clickRemovePassState, $scope.clickOkPassState); break;
                            case "IDCardImage": return $scope.clickIDCardRemovePassState = true, $scope.selectedUser.IdCardCertificated = getStateResult($scope.clickIDCardRemovePassState, $scope.clickIDCardOkPassState); break;
                            case "DrivingLicenseImage": return $scope.clickDrivingLicenseRemovePassState = true, $scope.selectedUser.DrivingLicenseCertificated = getStateResult($scope.clickDrivingLicenseRemovePassState, $scope.clickDrivingLicenseOkPassState); break;
                            case "VehicleLicenseImage": return $scope.clickVehicleLicenseRemovePassState = true, $scope.selectedUser.VehicleLicenseCertificated = getStateResult($scope.clickVehicleLicenseRemovePassState, $scope.clickVehicleLicenseOkPassState); break;
                        }

                    }
                    $scope.selectedUser.IDCardImage = $scope.selectedUser.IDCardImage || "img/a0.jpg";
                    $scope.selectedUser.DrivingLicenseImage = $scope.selectedUser.DrivingLicenseImage || "img/a0.jpg";
                    $scope.selectedUser.VehicleLicenseImage = $scope.selectedUser.VehicleLicenseImage || "img/a0.jpg";
                    $scope.selectedUser.RealHeadImage = $scope.selectedUser.RealHeadImage || "img/a0.jpg"
                }
                catch (e) {
                    $ngBootbox.alert(e);
                }
            }, function (rej) {
                $ngBootbox.alert(rej);
            });
        }
        Detail($stateParams);
        //获取详情
        $scope.editUserDetail = function (user) {
            console.info('user', user);
            Detail(user);
        };

        var sasUrl;
        dataService.AquireStorageSharedSigniture('avatar-container').then(function (res) {
            console.info('SAS URL:', res);
            sasUrl = res.data.Response.StorageSharedSigniture;
        }, function (rej) { console.info('error SAS', rej); })
        
        var selectedFile = null; var selectedFileRealHead = null; var selectedFileIDCard = null; var selectedFileDrivingLicense = null; var selectedFileVehicleLicense = null;
        var submitUri = null; var submitRealHeadUri = null; var submitIDCardUri = null; var submitDrivingLicenseUri = null; var submitVehicleLicenseUri = null;
        $("#file1").bind('change', 'img1', handleFileSelect);
        $("#f").bind('change', 'VehicleLicense', handleFileSelect);
        $('#uploaderDriving').bind('change', 'uploaderDriving', handleFileSelect);
        $('#uploaderDriving').bind('change', 'uploaderDriving', handleFileSelect);
        $('#idCard').bind('change', 'IDCard', handleFileSelect);
        $('#realHead').bind('change', 'RealHead', handleFileSelect);

        if (window.File && window.FileReader && window.FileList && window.Blob) {
            // Great success! All the File APIs are supported.
        } else {
            alert('The File APIs are not fully supported in this browser.');
        }
        //Read the file and find out how many blocks we would need to split it.
        function handleFileSelect(e) {
            var files = e.target.files;
            console.info('files', files);
            //selectedFile = files[0];
            var baseUrl = sasUrl;
            var indexOfQueryStart = baseUrl.indexOf("?");
            //submitUri = baseUrl.substring(0, indexOfQueryStart) + '/' + selectedFile.name + baseUrl.substring(indexOfQueryStart);
            console.log(submitUri);
            //testee
            var objUrl = getObjectURL(this.files[0]);
            console.log("objUrl = " + objUrl);
            
            switch (e.data) {
                case 'img0':
                    return $("#img0").attr("src", objUrl);
                case 'VehicleLicense':
                    return $("#VehicleLicense").attr("src", objUrl), $('#ssss').css('display', 'inline'), selectedFileVehicleLicense = files[0], submitVehicleLicenseUri = baseUrl.substring(0, indexOfQueryStart) + '/' + selectedFileVehicleLicense.name + baseUrl.substring(indexOfQueryStart); break;
                case 'uploaderDriving':
                    return $('#DrivingLicense').attr('src', objUrl), $('#uploaderDriveRemove').css('display', 'inline'), selectedFileDrivingLicense = files[0], submitDrivingLicenseUri = baseUrl.substring(0, indexOfQueryStart) + '/' + selectedFileDrivingLicense.name + baseUrl.substring(indexOfQueryStart); break;
                case 'IDCard':
                    return $('#IDCard').attr('src', objUrl), $('#uploaderIDCardRemove').css('display', 'inline'), selectedFileIDCard = files[0], submitIDCardUri = baseUrl.substring(0, indexOfQueryStart) + '/' + selectedFileIDCard.name + baseUrl.substring(indexOfQueryStart); break;
                case 'RealHead':
                    return $('#RealHead').attr('src', objUrl), $('#uploaderRealHead').css('display', 'inline'), selectedFileRealHead = files[0], submitRealHeadUri = baseUrl.substring(0, indexOfQueryStart) + '/' + selectedFileRealHead.name + baseUrl.substring(indexOfQueryStart); break;
            }
            
        }
        //建立一個可存取到該file的url
        function getObjectURL(file) {
            var urlImg = null;
            if (window.createObjectURL != undefined) { // basic
                urlImg = window.createObjectURL(file);
            } else if (window.URL != undefined) { // mozilla(firefox)
                urlImg = window.URL.createObjectURL(file);
            } else if (window.webkitURL != undefined) { // webkit or chrome
                urlImg = window.webkitURL.createObjectURL(file);
            }
            return urlImg;
        }
        //实名头像
        $scope.uploaderRealHead = function () {
            console.info('selectedFileRealHead', selectedFileRealHead);
            console.info('submitRealHeadUri', submitRealHeadUri);
            upload(submitRealHeadUri, selectedFileRealHead, 'RealHead');
        }
        //身份证
        $scope.uploaderIDCard = function () {
            console.info('selectedFileIDCard', selectedFileIDCard);
            console.info('submitIDCardUri', submitIDCardUri);
            upload(submitIDCardUri, selectedFileIDCard, 'IDCard');
        }
        //驾驶证
        $scope.uploaderDrivingLicense = function () {
            console.info('selectedFileDrivingLicense', selectedFileDrivingLicense);
            console.info('submitDrivingLicenseUri', submitDrivingLicenseUri);
            upload(submitDrivingLicenseUri, selectedFileDrivingLicense, 'DrivingLicense');
        }
        //行驶证
        $scope.uploadFileInBlocks12 = function () {
            console.info('selectedFileVehicleLicense', selectedFileVehicleLicense);
            console.info('submitVehicleLicenseUri', submitVehicleLicenseUri);
            upload(submitVehicleLicenseUri, selectedFileVehicleLicense, 'VehicleLicense');
        }
        function upload(submitUri, selectedFile,result) {
            azureBlob.upload({
                baseUrl: submitUri,
                sasToken: 'avatar-container',
                file: selectedFile,
                progress: function (data, status) {
                    console.log('test progress data', data);
                    console.log('test progress status', status);
                },
                complete: function (data, status) {
                    console.log('test complete data', data);
                    console.log('test complete status', status);
                    console.info('result', result);
                    switch (result) {
                        case 'RealHead': return $('#RealHeadUploadSuccess').css('color', '#5CB85C'), $scope.RealHeadImage = submitUri; break;
                        case 'IDCard': return $('#IDCardUploadSuccess').css('color', '#5CB85C'), $scope.IDCardImage = submitUri; break;
                        case 'DrivingLicense': return $('#DrivingLicenseUploadSuccess').css('color', '#5CB85C'), $scope.DrivingLicenseImage = submitUri; break;
                        case 'VehicleLicense': return $('#VehicleLicenseUploadSuccess').css('color', '#5CB85C'), $scope.VehicleLicenseImage = submitUri; break;
                    } 
                },
                error: function (xhr, desc, err) {
                    console.log('test error desc', desc);
                    console.log('test error err', err);
                },
                blockSize: 1024 * 32,
            })
        }

        //编辑（保存）
        $scope.EditUserInfo = function () {
            console.info('$scope.RealHeadImage', $scope.RealHeadImage);
            console.info('$scope.IDCardImage', $scope.IDCardImage);
            console.info('$scope.DrivingLicenseImage', $scope.DrivingLicenseImage);
            console.info('$scope.VehicleLicenseImage', $scope.VehicleLicenseImage);
            var list = {
                UserId: $scope.selectedUser.UserId,
                CarCode: $scope.selectedUser.CarCode,
                DrivingLicenseKeyStatus: $scope.selectedUser.DrivingLicenseCertificated,
                RealHeadKeyStatus: $scope.selectedUser.RealHeadImageCertificated,
                IdCardKeyStatus: $scope.selectedUser.IdCardCertificated,
                VehicleLicenseKeyStatus: $scope.selectedUser.VehicleLicenseCertificated
            };
            dataService.putUserRealNameCertificationStatus(list).then(function (res) {
                loadUsers($scope.searchingKeyword, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingRoleId, $scope.searchingState, paginationOptions.pageNumber, paginationOptions.pageSize, false);
                Detail({ 'UserId': $scope.selectedUser.UserId, 'RealName': $scope.selectedUser.RealName, 'UserName': $scope.selectedUser.UserNameReal, 'PhoneNumber': $scope.selectedUser.PhoneNumber, 'Roles': $scope.RolesCheckedList });
            }, function (rej) { $ngBootbox.alert(rej); });
        };

    }]);

})();